package com.Cfeng.XiaohuanChat.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;

/**
 * @author Cfeng
 * @date 2022/8/22
 * 访问http://wthrcdn.etouch.cn/获取天气信息
 */
@Slf4j
public class WeatherUtil {

    //获取天气信息,返回JSON字符串
    public static String getWheatherByCity(String city) {
        String url = "http://wthrcdn.etouch.cn/weather_mini?city="+city;
        //解析获得数据
        String res = loadUrl(url);
//        JSONObject res =  JSONObject.parseObject(result);
        log.info("天气信息：{}",res.toString());
        return res.toString();
    }

    //将url返回的数据写入字符串
    private static String loadUrl(String url) {
        StringBuilder stringBuilder = new StringBuilder();

        try {
            //创建链接地址
            URL region = new URL(url);
            //访问链接URL地址
            URLConnection connection = region.openConnection();
            //读取url缓冲，这里需要使用GZIPInputStream压缩输入流读取连接的流
            BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()),"utf-8"));
            //读取流写入字符串
            String inputLine = null;
            //读取到末尾
            while((inputLine = reader.readLine()) != null) {
                stringBuilder.append(inputLine);
            }
            reader.close();
        } catch (Exception e) {
            log.error("出错了：{}",e.getMessage());
        }
        return stringBuilder.toString();
    }
}
